package com.example.cangzhou.controller;


import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.cangzhou.context.BaseContext;
import com.example.cangzhou.entity.Resource;
import com.example.cangzhou.result.Result;
import com.example.cangzhou.service.ResourceService;
import com.example.cangzhou.utils.LocalUtil;
import com.example.cangzhou.vo.FileVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.Collections;
import java.util.List;
import java.util.Random;
import java.util.stream.Collectors;


@RestController
@RequestMapping("/resource")
public class ResourceController {

    @Autowired
    private ResourceService resourceService;

    @Autowired
    private LocalUtil localUtil;

    /**
     * 上传文件
     */
    @PostMapping("/upload")
    public Result<String> upload(@RequestParam("file") MultipartFile file, FileVO fileVO) {
        if (file == null || !StringUtils.hasText(fileVO.getType())) {
            return Result.error("文件和资源类型和资源路径不能为空！");
        }

        fileVO.setFile(file);
        // 设置原始文件名
        if (fileVO.getOriginalName() == null) {
            fileVO.setOriginalName(file.getOriginalFilename());
        }
        // 设置文件大小
        if (fileVO.getSize() == null) {
            fileVO.setSize(file.getSize());
        }
        
        fileVO.setRelativePath(fileVO.getType() + "/" + System.currentTimeMillis() + "_" + new Random().nextInt(1000));
        FileVO result = localUtil.saveFile(fileVO);

        Resource re = new Resource();
        re.setPath(result.getVisitPath());
        re.setType(fileVO.getType());
        re.setSize(fileVO.getSize() != null ? fileVO.getSize().intValue() : Integer.valueOf(Long.toString(file.getSize())));
        re.setOriginalName(fileVO.getOriginalName());
        re.setUserId(Math.toIntExact(BaseContext.getCurrentId()));
        resourceService.save(re);
        return Result.success(result.getVisitPath());
    }

    /**
     * 保存
     */
    @PostMapping("/saveResource")
    public Result saveResource(@RequestBody Resource resource) {
        if (!StringUtils.hasText(resource.getType()) || !StringUtils.hasText(resource.getPath())) {
            return Result.error("资源类型和资源路径不能为空！");
        }
        Resource re = new Resource();
        re.setPath(resource.getPath());
        re.setType(resource.getType());
        re.setSize(resource.getSize());
        re.setOriginalName(resource.getOriginalName());
        re.setUserId(Math.toIntExact(BaseContext.getCurrentId()));
        resourceService.save(re);
        return Result.success();
    }

    /**
     * 删除
     */
    @PostMapping("/deleteResource")
    public Result deleteResource(@RequestParam("path") String path) {
        Resource resource = resourceService.lambdaQuery().eq(Resource::getPath, path).one();
        if (resource == null) {
            return Result.error("文件不存在：" + path);
        }

        localUtil.deleteFile(Collections.singletonList(path));
        return Result.success();
    }


    /**
     * 查询资源
     */
    @PostMapping("/listResource")
    public Result<Page> listResource(@RequestBody Resource resource, @RequestParam Integer pageNum, @RequestParam Integer pageSize) {
        Page<Resource> page = resourceService.lambdaQuery()
                .eq(StringUtils.hasText(resource.getType()), Resource::getType, resource.getType())
                .orderByDesc(Resource::getCreateTime).page(new Page<>(pageNum, pageSize));
        return Result.success(page);
    }

    /**
     * 修改资源状态
     */
    @GetMapping("/changeResourceStatus")
    public Result changeResourceStatus(@RequestParam("id") Integer id, @RequestParam("flag") Boolean flag) {
        resourceService.lambdaUpdate().eq(Resource::getId, id).set(Resource::getStatus, flag).update();
        return Result.success();
    }


}

